package com.huifaapp.mall.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.google.gson.Gson;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.ShoppingCartAdapter;
import com.huifaapp.mall.adapter.TmallchoicenessAdapter;
import com.huifaapp.mall.adapter.TmallchoicenessListAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.GoodsSkuCountBean;
import com.huifaapp.mall.bean.InviteCollarNow;
import com.huifaapp.mall.bean.JDcomjPlistBean;
import com.huifaapp.mall.bean.JDlianjie;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.bean.UserMyShoppingCart;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.MyListView;
import com.huifaapp.mall.uitils.ShareUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;

/**
 * Created by an on 2017/6/14.
 * 购物车界面
 *
 */
public class ShopCartActivity extends Activity implements View.OnClickListener
        , ShoppingCartAdapter.CheckInterface, ShoppingCartAdapter.ModifyCountInterface ,ShoppingCartAdapter.ModifyCountInter{
    private static final String TAG = "ShoppingCartActivity";
    Button btnBack;
   //全选
    CheckBox ckAll;
    //总额
    TextView tvShowPrice;
   //结算
    TextView tvSettlement;
   //编辑
    TextView btnEdit;//tv_edit
    MyListView list_shopping_cart;
    private ShoppingCartAdapter shoppingCartAdapter;
    private boolean flag = false;
    private LinearLayout ll_shopcart_pay;
    private LinearLayout ll_shopcart_dele;
    ArrayList<UserMyShoppingCart> list;

    private boolean mSelect;
    private double totalPrice = 0.00;// 购买的商品总价
    private double totalPrice1 = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    private TextView tv_show_price_dete;
    private TextView tv_settlement_dete;
    ArrayList<String> ListId=new ArrayList<>();
    ArrayList<String> ListgoodsId=new ArrayList<>();
    ArrayList<String> listSkuidCount=new ArrayList<String>();

    private  String  GOODSURL=ApiManager.BASE_NIUPAI_URL+"yh"+"/goods";//，精选，爆品二合一接口
    private  String GETCONURLURL=ApiManager.BASE_NIUPAI_URL+"yh"+"/getConUrl";//京东获取优惠劵二合一链接
    private  String SYNCJDSPREADURL=ApiManager.BASE_NIUPAI_URL+"yh"+"/getUrl";//京东普通二合一链接
    private List<JDcomjPlistBean.DataBean.ListBean> jDcomjPlistlist;;
    private XRecyclerView mRecyclerview,list_xrecyclerView;
    private TmallchoicenessAdapter myRecycleViewAdapter;
    private  int curr;
    private static final int SHARET_WXHY = 517;
    ArrayList<String> idlist = new ArrayList<>();
    ArrayList<String> idlistlv = new ArrayList<>();
    private int lvgv=0;
    private JDlianjie jDlianjiebean;
    private int location;
    private String datayouhui;
    private String datalisnajie;
    private ImageView floatingActionButton;
    private ImageView dialog_tmall_floatingActionButton_share;
    public boolean isSelected = true;
    private View inflate;
    private TmallchoicenessListAdapter tmallchoicenessListAdapter;
    public static Map<Integer, Boolean> hmap;
    private ImageView iv_gouwuche_isnull;
    private LinearLayout rl_bottom;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shopweinituijian);
        hmap = new HashMap<>();
        initView();
        ImageLoader imageLoader= ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
    }

    @Override
    protected void onResume() {
        super.onResume();
        tvShowPrice.setText("0.00");
        ckAll.setChecked(false);
        Loadshopcart();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        tvShowPrice.setText("0.00");
        ckAll.setChecked(false);
        Loadshopcart();
    }

    private void initView() {

        jDcomjPlistlist = new ArrayList<JDcomjPlistBean.DataBean.ListBean>();
        mRecyclerview = (XRecyclerView)findViewById(R.id.shopweiniyuijian_XRecyclerView);
        list_xrecyclerView=(XRecyclerView)findViewById(R.id.list_xrecyclerView_Q);
        rl_bottom= (LinearLayout) findViewById(R.id.rl_bottom);
        myRecycleViewAdapter = new TmallchoicenessAdapter(jDcomjPlistlist, this, "shop");
        mRecyclerview.setLayoutManager(new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false));
        mRecyclerview.setAdapter(myRecycleViewAdapter);
        mRecyclerview.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                curr = 0;
                initjplistHttp();
            }

            @Override
            public void onLoadMore() {
                curr++;
                initjplistHttp();
            }
        });

        tmallchoicenessListAdapter = new TmallchoicenessListAdapter(this, jDcomjPlistlist, "shop");
        list_xrecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        list_xrecyclerView.setAdapter(tmallchoicenessListAdapter);
        list_xrecyclerView.setVisibility(View.GONE);
        list_xrecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                curr = 0;
                initjplistHttp();
            }

            @Override
            public void onLoadMore() {
                curr++;
                initjplistHttp();
            }
        });
        initjplistHttp();
        floatingActionButton = (ImageView) findViewById(R.id.dialog_tmall_floatingActionButton_Q);
//        dialog_tmall_floatingActionButton_share = (FloatingActionButton) mview.findViewById(R.id.dialog_tmall_floatingActionButton_share);
        dialog_tmall_floatingActionButton_share = (ImageView) findViewById(R.id.dialog_tmall_floatingActionButton_share_Q);
        shoppingCartAdapter = new ShoppingCartAdapter(ShopCartActivity.this);
        if (SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
            dialog_tmall_floatingActionButton_share.setVisibility(View.VISIBLE);
        }else {
            dialog_tmall_floatingActionButton_share.setVisibility(View.GONE);
        }
        inflate = View.inflate(this, R.layout.layout_shopping_cart_activity, null);
        mRecyclerview.addHeaderView(inflate);
        list_xrecyclerView.addHeaderView(inflate);
        btnBack= (Button) inflate. findViewById(R.id.btn_back);
        ckAll= (CheckBox) findViewById(R.id.ck_all);
        iv_gouwuche_isnull= (ImageView) inflate.findViewById(R.id.iv_gouwuche_isnull);
        tvShowPrice= (TextView)  findViewById(R.id.tv_show_price);
        tvSettlement= (TextView) findViewById(R.id.tv_settlement);
        btnEdit= (TextView) inflate.  findViewById(R.id.bt_header_right);
        list_shopping_cart= (MyListView) inflate.  findViewById(R.id.list_shopping_cart);
        ll_shopcart_pay= (LinearLayout) findViewById(R.id.ll_shopcart_pay);
        ll_shopcart_dele= (LinearLayout)   findViewById(R.id.ll_shopcart_dele);
        tv_show_price_dete= (TextView) findViewById(R.id.tv_show_price_dete);
        tv_settlement_dete= (TextView) findViewById(R.id.tv_settlement_dete);
        btnEdit.setOnClickListener(this);
        ckAll.setOnClickListener(this);
        tvSettlement.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        tv_show_price_dete.setOnClickListener(this);
        tv_settlement_dete.setOnClickListener(this);
        initData();
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isSelected) {
                    isSelected = false;
                    mRecyclerview.setVisibility(View.GONE);
                    list_xrecyclerView.setVisibility(View.VISIBLE);
                    //scrollToPosition();
                    mRecyclerview.removeView(inflate);
                    lvgv=1;
                    floatingActionButton.setImageResource(R.drawable.btn_blue_qiehuan_1);

                } else {
                    isSelected = true;
                    list_xrecyclerView.setVisibility(View.GONE);
                    mRecyclerview.setVisibility(View.VISIBLE);
                    // scrollToPosition();
                    list_xrecyclerView.removeView(inflate);
                    lvgv=0;
                    floatingActionButton.setImageResource(R.drawable.btn_icon_leibiao);
                }
            }
        });

        //分享按钮
        dialog_tmall_floatingActionButton_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(lvgv==0) {
                    Log.e("数据Toady", Contig.checkedIndexltmalgrid + "-=====Contig.checkedIndex===id");
                    if (Contig.checkedIndexltmalgrid.size() == 0) {
                        Toast.makeText(ShopCartActivity.this, "没有选择，请选择再分享！", Toast.LENGTH_SHORT).show();
                    } else {
                        for (int i = 0; i < Contig.checkedIndexltmalgrid.size(); i++)
                            idlist.add(jDcomjPlistlist.get(Contig.checkedIndexltmalgrid.get(i)).getId());

                        Log.e("数据Toady", idlist + "-===========id");


                        StringBuffer permission = new StringBuffer();
                        for (int i = 0; i < idlist.size(); i++) {
                            if (i == 0) {
                                permission.append(idlist.get(i));
                            } else {
                                permission.append("," + idlist.get(i));
                            }
                            Contig.listididtml.add(idlist.get(i));

                        }
//                    LoadStoreList(0, 0, Contig.listidid);

                        ApiManager
                                .getInstance()
                                .getApiServer()
                                .getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(ShopCartActivity.this), permission.toString())
                                .compose(ApiManager.<ShareImageBean>handlResult())
                                .subscribe(new ObserverCallback<ShareImageBean>(ShopCartActivity.this) {
                                    @Override
                                    protected void onSuccessful(ShareImageBean resp) {


                                        saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);
                                        if (Contig.checkedIndexltmalgrid.size() > 0) {
                                            for (int a = 0; a < Contig.checkedIndexltmalgrid.size(); a++) {
                                                Contig.ShareListtmll.add(jDcomjPlistlist.get(Contig.checkedIndexltmalgrid.get(a)).getId());
                                            }
                                        }

                                        myRecycleViewAdapter = new TmallchoicenessAdapter(jDcomjPlistlist, ShopCartActivity.this,"shop");
                                        mRecyclerview.setLayoutManager(new GridLayoutManager(ShopCartActivity.this, 2, GridLayoutManager.VERTICAL, false));
                                        mRecyclerview.setAdapter(myRecycleViewAdapter);
                                    }


                                    @Override
                                    protected void onError(String code, String errMsg) {
                                        ToastUtils.showShortSafe(errMsg);
                                    }
                                });
                        idlist.clear();
                    }
                }else if(lvgv==1){
                    Log.e("数据Toady", Contig.checkedIndexltmallist + "-=====Contig.checkedIndex===id");
                    if (Contig.checkedIndexltmallist.size() == 0) {
                        Toast.makeText(ShopCartActivity.this, "没有选择，请选择再分享！", Toast.LENGTH_SHORT).show();
                    } else {
                        for (int i = 0; i < Contig.checkedIndexltmallist.size(); i++)
                            idlistlv.add(jDcomjPlistlist.get(Contig.checkedIndexltmallist.get(i)).getId());

                        Log.e("数据Toady", idlistlv + "-===========id");


                        StringBuffer permission = new StringBuffer();
                        for (int i = 0; i < idlistlv.size(); i++) {
                            if (i == 0) {
                                permission.append(idlistlv.get(i));
                            } else {
                                permission.append("," + idlistlv.get(i));
                            }
                            Contig.listididlisttml.add(idlistlv.get(i));

                        }
//                    LoadStoreList(0, 0, Contig.listidid);

                        ApiManager
                                .getInstance()
                                .getApiServer()
                                .getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(ShopCartActivity.this), permission.toString())
                                .compose(ApiManager.<ShareImageBean>handlResult())
                                .subscribe(new ObserverCallback<ShareImageBean>(ShopCartActivity.this) {
                                    @Override
                                    protected void onSuccessful(ShareImageBean resp) {

                                        saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);
                                        if (Contig.checkedIndexltmallist.size() > 0) {
                                            for (int a = 0; a < Contig.checkedIndexltmallist.size(); a++) {
                                                Contig.ShareListlvtmll.add(jDcomjPlistlist.get(Contig.checkedIndexltmallist.get(a)).getId());
                                            }
                                        }

                                        tmallchoicenessListAdapter = new TmallchoicenessListAdapter(ShopCartActivity.this, jDcomjPlistlist,"shop");
                                        list_xrecyclerView.setLayoutManager(new LinearLayoutManager(ShopCartActivity.this, LinearLayoutManager.VERTICAL, false));
                                        list_xrecyclerView.setAdapter(tmallchoicenessListAdapter);
                                    }

                                    @Override
                                    protected void onError(String code, String errMsg) {
                                        ToastUtils.showShortSafe(errMsg);
                                    }
                                });
                        idlistlv.clear();
                    }
                }

            }
        });

    }
    private void saveImage(List<String> imageUrls, final String cconten, final int type) {

        Log.v("shiran", "------------saveImage------------");

        final LoadingDialog dialog = new LoadingDialog(ShopCartActivity.this);
        dialog.setContent("正在生成图片请稍后");


        Observable.just(imageUrls)
                .map(new Function<List<String>, List<String>>() {

                    @Override
                    public List<String> apply(List<String> list) throws Exception {

                        List<String> paths = new ArrayList<String>();
                        for (String s : list) {
                            FutureTarget<File> future = Glide.with(APP.getInstance())
                                    .load(s)
                                    .downloadOnly(500, 500);
                            File cacheFile = future.get();
                            String uuid = UUID.randomUUID().toString();
                            FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
                            String pat = savePath + uuid + ".jpg";
                            paths.add(pat);

                        }


                        return paths;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }
                    }

                    @Override
                    public void onNext(List<String> value) {
                        LogUtils.e(value);
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }

                        switch (type) {
                            case SHARET_WXHY:


                                ShareUtils.sharePicToFriendNoSDK(ShopCartActivity.this, value);
//                                        ClipboardUtils.copyText(cconten);
//                                        ToastUtils.showShortSafe("内容已复制!");
                                break;
//                            case SHARET_WXPYQ:
//                                ShareUtils.share9PicsToWXCircle(getActivity(), "", value);
//                                break;
                            default:

                                break;
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }
                });
    }
    private void initjplistHttp() {
        Log.e("优惠",GOODSURL+"?type=jing"+"&start="+curr+"&length=10");
        OkHttpUtils.post().url(GOODSURL).addParams("type","jing").addParams("start", curr+"").addParams("length",10+"").build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                mRecyclerview.refreshComplete();
                initDatalist(response);

            }
        });
    }

    private void initDatalist(String response) {
        mRecyclerview.refreshComplete();
        Log.e("精选", response);
        Gson gson = new Gson();
        final JDcomjPlistBean jDcomjPlistBean = gson.fromJson(response, JDcomjPlistBean.class);
        if (jDcomjPlistBean != null && jDcomjPlistBean.getData() != null && jDcomjPlistBean.getData().getList() != null) {
            if (curr == 0) {
                jDcomjPlistlist.clear();
            }
            jDcomjPlistlist.addAll(jDcomjPlistBean.getData().getList());
            myRecycleViewAdapter.notifyDataSetChanged();
            myRecycleViewAdapter.setmMyItemclickListener(new TmallchoicenessAdapter.MyItemclickListener() {
                @Override
                public void itemclick(View view, int position) {
                    location = position;

                        Intent intent = new Intent(ShopCartActivity.this, Red_PacketActivity.class);
                        intent.putExtra("shopid", jDcomjPlistlist.get(position).getId());
                        intent.putExtra("typex", "yh");
                        startActivity(intent);

                }
            });
            tmallchoicenessListAdapter.notifyDataSetChanged();
            tmallchoicenessListAdapter.setmMylistItemclickListener(new TmallchoicenessListAdapter.MylistItemclickListener() {
                @Override
                public void listitemclick(View view, int position) {
                    Intent intent = new Intent(ShopCartActivity.this, Red_PacketActivity.class);
                    intent.putExtra("shopid", jDcomjPlistlist.get(position).getId());
                    intent.putExtra("typex", "yh");
                    startActivity(intent);
                }
            });

        }
    }

    //初始化数据
    protected void initData() {



        Loadshopcart();

    }

    @Override
    protected void onStart() {
        super.onStart();
        tvShowPrice.setText("0.00");
        ckAll.setChecked(false);
        listSkuidCount.clear();
        ListId.clear();
        ListgoodsId.clear();

    }


//    @Override
//    protected void onRestart() {
//        super.onRestart();
//        listSkuidCount.clear();
//        ListId.clear();
//    }
    private void Loadshopcart(){
        Log.e("ShopCartActivity","url========="+ApiManager.USERS_MYSHOPPINGCART+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(ShopCartActivity.this));
        OkHttpUtils.get().url(ApiManager.USERS_MYSHOPPINGCART+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(ShopCartActivity.this)).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
//                    Gson gson = new Gson();
//                     list = gson.fromJson(response,UserMyShoppingCart.class);
                    JSONObject obj=new JSONObject(response);
                    String data=obj.getString("data");
                    if (obj.getString("code").equals("10000")) {
                       list = UserMyShoppingCart.newInstanceList(data);
                        if(list.size()==0||list.equals("")){
                            iv_gouwuche_isnull.setVisibility(View.VISIBLE);
                            list_shopping_cart.setVisibility(View.GONE);
                            rl_bottom.setVisibility(View.GONE);
                        }else{
                            iv_gouwuche_isnull.setVisibility(View.GONE);
                            list_shopping_cart.setVisibility(View.VISIBLE);
                            rl_bottom.setVisibility(View.VISIBLE);
                        }

                       shoppingCartAdapter.setCheckInterface(ShopCartActivity.this);
                        shoppingCartAdapter.setModifyCountInterface(ShopCartActivity.this);
                       shoppingCartAdapter.setModifyCountInter(ShopCartActivity.this);
                                list_shopping_cart.setAdapter(shoppingCartAdapter);
                                shoppingCartAdapter.setShoppingCartBeanList(list);


                    }else if(obj.getString("code").equals("10001")){
                        Toast.makeText(ShopCartActivity.this,obj.getString("msg"),Toast.LENGTH_SHORT).show();
                        Intent intent=new Intent(ShopCartActivity.this,LoginActivity.class);
                        startActivity(intent);
                    }else{
                        Toast.makeText(ShopCartActivity.this,obj.getString("msg"),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
//                Gson gson = new Gson();
//                UserMyShoppingCart list = gson.fromJson(response,UserMyShoppingCart.class);
//
//                if(list.getCode().equals("10000")) {
//                shoppingCartAdapter = new ShoppingCartAdapter(ShopCartActivity.this);
//                shoppingCartAdapter.setCheckInterface(ShopCartActivity.this);
//                shoppingCartAdapter.setModifyCountInterface(ShopCartActivity.this);
//                list_shopping_cart.setAdapter(shoppingCartAdapter);
//                shoppingCartAdapter.setShoppingCartBeanList(list.getData());
//                }else{
//                    Toast.makeText(ShopCartActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
//                }
            }
        });
    }
    int position = 0;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //全选按钮
            case R.id.ck_all:
                try {
                    if (list.size() != 0) {

                        if (ckAll.isChecked()) {

                            for (int i = 0; i < list.size(); i++) {
                                list.get(i).setChoosed(true);
                            }
                            shoppingCartAdapter.notifyDataSetChanged();
                        } else {

                            for (int i = 0; i < list.size(); i++) {
                                list.get(i).setChoosed(false);
                            }
                            shoppingCartAdapter.notifyDataSetChanged();
                        }
                    }
                    statistics();
                }catch (Exception e){
                    Log.e("数据",e.getMessage());
                }
                break;
            case R.id.bt_header_right:
                flag = !flag;
                if (flag) {
                    btnEdit.setText("完成");
                    shoppingCartAdapter.isShow(false);
                    ckAll.setChecked(false);
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setChoosed(false);
                    }
                    ll_shopcart_pay.setVisibility(View.GONE);
                    ll_shopcart_dele.setVisibility(View.VISIBLE);
                } else {
                    btnEdit.setText("编辑");
                    tvShowPrice.setText("0.00");
                    ckAll.setChecked(false);
                    shoppingCartAdapter.notifyDataSetChanged();
                    shoppingCartAdapter.isShow(true);
//                    ckAll.setChecked(true);
                    ll_shopcart_pay.setVisibility(View.VISIBLE);
                    ll_shopcart_dele.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_settlement: //结算

                lementOnder();
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.tv_show_price_dete:
                ListgoodsId.clear();
                //选中的需要提交的商品清单
                for (UserMyShoppingCart bean:list ){
                    boolean choosed = bean.isChoosed();
                    if (choosed){
                        String shoppingName = bean.getGoodsName();
                        int count = bean.getCount();
                        double price = bean.getActualpay();
                        String attribute = bean.getParam();
                        String id = bean.getCouponId();

                        ListgoodsId.add(bean.getGoodsId());
                        Log.e("shopcartactivity",id+"----id---"+shoppingName+"---"+count+"---"+price+"--size----"+"--attr---"+attribute+ListgoodsId);
                    }
                }

                addcollect(ListgoodsId);
                break;
            case R.id.tv_settlement_dete:
                ListId.clear();

                //选中的需要提交的商品清单
                for (UserMyShoppingCart bean:list ){
                    boolean choosed = bean.isChoosed();
                    if (choosed){
                        String shoppingName = bean.getGoodsName();
                        int count = bean.getCount();
                        double price = bean.getActualpay();
                        String attribute = bean.getParam();
                        String id = bean.getCouponId();
                        position=1;

                        ListId.add(bean.getCartId());
                        Log.e("shopcartactivity",id+"----id---"+shoppingName+"---"+count+"---"+price+"--size----"+"--attr---"+attribute+ListId);
                    }
                }
                AlertDialog alert = new AlertDialog.Builder(ShopCartActivity.this).create();
                alert.setTitle("操作提示");
                alert.setMessage("您确定要将这些商品从购物车中移除吗？");
                alert.setButton(DialogInterface.BUTTON_NEGATIVE, "取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        });
                alert.setButton(DialogInterface.BUTTON_POSITIVE, "确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if(list.size()==2){
                                    list_shopping_cart.setVisibility(View.GONE);
                                    iv_gouwuche_isnull.setVisibility(View.VISIBLE);
                                    Loadshopcart();
                                    shoppingCartAdapter.notifyDataSetChanged();
                                }
                                if(list.size()==1){
                                    list_shopping_cart.setVisibility(View.GONE);
                                    iv_gouwuche_isnull.setVisibility(View.VISIBLE);
                                    Loadshopcart();
                                    shoppingCartAdapter.notifyDataSetChanged();
                                }
                                delete(ListId);
//                                childDelete(which);//删除 目前只是从item中移除
                                for (int z=0;z<list.size();z++){
                                    if(position==1) {

                                        list.remove(z);
                                        Loadshopcart();
                                        shoppingCartAdapter.notifyDataSetChanged();
                                        Loadshopcart();
                                        shoppingCartAdapter.notifyDataSetChanged();
                                        Loadshopcart();
                                        shoppingCartAdapter.notifyDataSetChanged();
                                        Loadshopcart();
                                        shoppingCartAdapter.notifyDataSetChanged();
                                        statistics();


//                                        shoppingCartAdapter.notifyDataSetChanged();

                                    }
                                }
                                ckAll.setChecked(false);
                            }
                        });
                alert.show();

                break;

        }
    }

    private void addcollect(ArrayList<String> ListgoodsId) {

        StringBuffer permission = new StringBuffer();
        for(int i=0;i<ListgoodsId.size();i++){
            if(i == 0){
                permission.append(ListgoodsId.get(i));
            }else{
                permission.append(","+ListgoodsId.get(i));
            }
        }
        Log.e("添加收藏",ApiManager.USERS_ADDCOLLECT+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(ShopCartActivity.this)+"&goodsId="+permission.toString());
        OkHttpUtils.get().url(ApiManager.USERS_ADDCOLLECT+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(ShopCartActivity.this)+"&goodsId="+permission.toString())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        InviteCollarNow list = gson.fromJson(response,InviteCollarNow.class);
                        if(list.getCode()=="10000"){
                            Toast.makeText(ShopCartActivity.this,"收藏成功",Toast.LENGTH_SHORT).show();
                            shoppingCartAdapter.notifyDataSetChanged();
                        }else if(list.getCode()=="10001"){
                            Intent intent=new Intent(ShopCartActivity.this,LoginActivity.class);
                            startActivity(intent);
                        }else{
                            Toast.makeText(ShopCartActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }

    private void delete(ArrayList<String> listId) {
        StringBuffer permission = new StringBuffer();
        for(int i=0;i<ListId.size();i++){
            if(i == 0){
                permission.append(ListId.get(i));
            }else{
                permission.append(","+ListId.get(i));
            }
        }
        Log.e("删除",ApiManager.DELSHOPPINGCART+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+ AUniqueIdentifier.getDeviceId(ShopCartActivity.this)+"&cartId="+permission.toString());
        OkHttpUtils.get().url(ApiManager.DELSHOPPINGCART+"?token="+ SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)+"&appId="+AUniqueIdentifier.getDeviceId(ShopCartActivity.this)+"&cartId="+permission.toString())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {

                    }

                    @Override
                    public void onResponse(String response) {
                        Gson gson = new Gson();
                        InviteCollarNow list = gson.fromJson(response,InviteCollarNow.class);
                        if(list.getCode()=="10000"){
                            Toast.makeText(ShopCartActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                            shoppingCartAdapter.notifyDataSetChanged();
                            Loadshopcart();
                        }else if(list.getCode()=="10001"){
                            Intent intent=new Intent(ShopCartActivity.this,LoginActivity.class);
                            startActivity(intent);
                        }else{
                            Toast.makeText(ShopCartActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }

    /**
     * 结算订单、支付
     */
    private void lementOnder() {
    //选中的需要提交的商品清单
        for (UserMyShoppingCart bean:list ){
            boolean choosed = bean.isChoosed();
            if (choosed){
                String shoppingName = bean.getGoodsName();
                int count = bean.getCount();
                double price = bean.getActualpay();
                String attribute = bean.getParam();
                String id = bean.getCouponId();

                ListId.add(bean.getCartId());
                listSkuidCount.add(bean.getGoodsId()+":"+count);
                Log.e("shopcartactivity",id+"----id---"+shoppingName+"---"+count+"---"+price+"--size----"+"--attr---"+attribute+ListId);
            }
        }

//        ToastUtil.showL(this,"总价："+totalPrice);
        Log.e("shopcartactivity",listSkuidCount+"listSkuidCount"+ListId);
        if(listSkuidCount.size()>0) {
            //跳转到支付界面
            Intent intent = new Intent(ShopCartActivity.this, DetailsofPaymentActivity.class);
            intent.putExtra("intent", "gwc");
            intent.putExtra("listSkuidCount", listSkuidCount);
            startActivity(intent);
        }
    }

    /**
     * 单选
     * @param position  组元素位置
     * @param isChecked 组元素选中与否
     */
    @Override
    public void checkGroup(int position, boolean isChecked) {
        list.get(position).setChoosed(isChecked);
        if (isAllCheck()) {
            ckAll.setChecked(true);
            shoppingCartAdapter.notifyDataSetChanged();
            statistics();
        }else {
            ckAll.setChecked(false);
            shoppingCartAdapter.notifyDataSetChanged();
            statistics();
        }
    }


    /**
     * 遍历list集合
     * @return
     */
    private boolean isAllCheck() {

        for (UserMyShoppingCart group : list) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }
    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {
        Log.e("list",list+"listlistlistlistlistlistlistlistlistlistlistlistlistlistlistlistlist");
        totalCount = 0;
        totalPrice = 0.00;
        totalPrice1=0.00;
       for (int i = 0; i < list.size(); i++) {
            UserMyShoppingCart shoppingCartBean = list.get(i);
            if (shoppingCartBean.isChoosed()) {
                totalCount++;
                if(shoppingCartBean.getIsRevice().equals("1")){
                    totalPrice+=shoppingCartBean.getActualpay()*shoppingCartBean.getCount();
                }else   if(shoppingCartBean.getIsRevice().equals("0")){
                    totalPrice += shoppingCartBean.getOriginPrice() * shoppingCartBean.getCount();
                }
                totalPrice1 = totalPrice;
            }
        }
        tvShowPrice.setText("¥"+totalPrice1);

//        tvSettlement.setText("结算(" + totalCount + ")");
    }
    private void Loadkucun(String goodsId, final int position, final View showCountView){
        Log.e("ShopCartActivity","库存url========="+ ApiManager.GOODS_SKU_COUNT+"?skuId="+goodsId);
        OkHttpUtils.get().url(ApiManager.GOODS_SKU_COUNT+"?skuId="+goodsId).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                GoodsSkuCountBean listskucount = gson.fromJson(response,GoodsSkuCountBean.class);
                UserMyShoppingCart shoppingCartBean = list.get(position);
                int currentCount = shoppingCartBean.getCount();
                Log.e("库存",""+listskucount.getData());
                if(currentCount<listskucount.getData()){
                currentCount++;
                }
                shoppingCartBean.setCount(currentCount);
                ((TextView) showCountView).setText(currentCount + "");
                shoppingCartAdapter.notifyDataSetChanged();
                statistics();
            }
        });
    }
    /**
     * 增加
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        Loadkucun(list.get(position).getGoodsId(),position,showCountView);

    }
    /**
     * 删减
     *
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        UserMyShoppingCart shoppingCartBean = list.get(position);
        int currentCount = shoppingCartBean.getCount();
        if (currentCount == 1) {
            return;
        }
        currentCount--;
        shoppingCartBean.setCount(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }
    /**
     * 删除
     *
     * @param position
     */
    @Override
    public void childDelete(int position) {
        list.remove(position);
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    @Override
    public void dolingquan(int position) {
        loadllprice(list.get(position).getCouponId(),list);
    }
    private void loadllprice(String couponId, List<UserMyShoppingCart> list) {
        String url=ApiManager.COUPON_RECEIVE+"?token="+SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN)
                +"&appId="+ AUniqueIdentifier.getDeviceId(ShopCartActivity.this)
                +"&couponId="+couponId+"&type="+"1";
        Log.e("优惠券","优惠券"+url);
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject obj=new JSONObject(response);
                    if(obj.getString("code").equals("10000")){

                        Loadshopcart();
                        Toast.makeText(ShopCartActivity.this,"领取成功！",Toast.LENGTH_SHORT).show();

                    }else{
                        Toast.makeText(ShopCartActivity.this,obj.getString("msg"),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

}
